<template lang="html">
  <article id="views-course_detail">
    <div class="shareLayer" v-show="isShowShareLayer" @click="toggleShowLayer()">
      <img class="arrow" src="../assets/image/share_arrow.png" alt="">
      <img class="text" src="../assets/image/share_text.png" alt="">
    </div>
    <Banner
      :class="{ filter: isShowShareLayer }"
      :banners="courseDetail ? courseDetail.subjectPicList : []"
    ></Banner>
    <CoachInfo
      :class="{ filter: isShowShareLayer }"
      :courseDetail="courseDetail"
    ></CoachInfo>
    <CourseDescription
     :class="{ filter: isShowShareLayer }"
     :description="courseDetail ? courseDetail.content : ''"
    ></CourseDescription>
    <DetailFooter
      :stepText="stepText"
      v-on:showShareLayer="toggleShowLayer"
      v-on:eNextStep="nextStep"
    ></DetailFooter>
  </article>
</template>

<script>
import utils from '@/lib/utils'
import superagent from 'superagent'
import authMiddleWare from '@/lib/auth-middleware'

const NEXT_STEP = ['cancel_queueing', 'has_bought', 'buy', 'queuing', 'end', 'pause']
export default {
  components: {
    Banner: require('@/components/course_detail/banner'),
    CoachInfo: require('@/components/course_detail/coach_info'),
    CourseDescription: require('@/components/course_detail/course_desc'),
    DetailFooter: require('@/components/course_detail/footer'),
  },
  data(){
    return {
      isShowShareLayer: false,
      stepType: NEXT_STEP[2],
      courseDetail: null
    }
  },
  computed: {
    stepText(){
      switch (this.stepType) {
        case NEXT_STEP[0]:
          return '取消排队'
          break;
        case NEXT_STEP[1]:
          return '查看预约'
          break;
        case NEXT_STEP[2]:
          return 'Confirm'
          break;
        case NEXT_STEP[3]:
          return '立即排队'
          break;
        case NEXT_STEP[4]:
          return '已结束'
          break;
        case NEXT_STEP[5]:
          return '即将降临'
          break;
      }
    }
  },
  methods: {
    toggleShowLayer(){//TODO: jssdk回调
      this.isShowShareLayer = !this.isShowShareLayer
    },
    getCourseDetail(){
      return new Promise((resolve, reject) => {
        superagent.post('/api/subject/info')
          .use(authMiddleWare())
          .query({ subjectId: this.$route.params.course_id })
          .end((err, res) => {
            if(res.ok){
              resolve(res.body.data)
            } else {
              reject(new Error('getCourseDetail error'))
            }
          })
      })
    },
    courseDetailFilter(data){
      let locations = data.location.split(',')
      data.location = {
        longitude: parseFloat(locations[0]),
        latitude: parseFloat(locations[1])
      }
      data.isEnd = Date.now() > data.endTime*1000
      return data
    },
    generateStepType(data){
      if(data.isEnd){
        return NEXT_STEP[4]
      } else if(data.status === 3){
        return NEXT_STEP[5]
      } else if(data.isQueue === 1){
        return NEXT_STEP[0]
      } else if(data.isBuy === 1){
        return NEXT_STEP[1]
      } else if(data.number > 0){
        return NEXT_STEP[2]
      } else if(data.number <= 0){
        return NEXT_STEP[3]
      }
    },
    nextStep(){
      let self = this
      switch (this.stepType) {
        case NEXT_STEP[0]:
          utils.modal({
            title: '是否取消排队',
            desc: '取消排队的退款将原路返还',
            callback: function(){
              self.drawback()
            }
          })
          break;
        case NEXT_STEP[1]:
          this.$router.push({ path: `/order/${this.courseDetail.orderId}` })
          // console.info('已购买，跳转到order')
          break;
        case NEXT_STEP[2]:
          // console.info('可购买，跳转到confirm页')
          this.$router.push({ path: `/confirm/${this.$route.params.course_id}` })
          break;
        case NEXT_STEP[3]:
          utils.modal({
            title: '排队预约需预先支付',
            desc: '当有人退款即报名成功，若无人退课款项原路返还',
            callback: function(){
              self.$router.push({ path: `/confirm/${self.$route.params.course_id}` })
              // console.log('排队，确认后跳转到confirm页');
            }
          })
          break;
        case NEXT_STEP[4]:
          utils.modal({
            title: '已结束',
            desc: '课程已结束，敬请期待下一期'
          })
          break;
        case NEXT_STEP[5]:
          utils.modal({
            title: '即将降临',
            desc: '近期即将开发报名，敬请关注'
          })
          break;
      }
    },
    drawback(){
      this.requestForDrawback(this.courseDetail.orderId)
      .then(data => {
        let self = this
        utils.modal({
          title: '取消排队',
          desc: '即将跳转至首页',
          callback: function(){
            self.$router.push({ path: '/' })
          }
        })
      })
      .catch(e => {
        if(!!e && e.errMsg){
          utils.modal({
            title: '取消排队失败',
            desc: e.errMsg,
          })
        }
      })
    },
    requestForDrawback(orderId){
      return new Promise((resolve, reject) => {
        superagent.post('/api/WxCommon/refund')
          .use(authMiddleWare())
          .query({ orderId })
          .end((err, res) => {
            if(res.ok){
              resolve(res.body.data)
            } else {
              if(!!res.body.data){
                reject(res.body.data)
              } else {
                reject('drawback error')
              }
            }
          })
      })
    },
  },
  created(){
    this.getCourseDetail()
    .then(courseDetail => {
      this.courseDetail = this.courseDetailFilter(courseDetail)

      this.stepType = this.generateStepType(courseDetail)
    })
  },
}
</script>

<style lang="scss" scoped>
@import "../css/config";
#views-course_detail{
  width: 100%;
  min-height: 100%;
  box-sizing: border-box;
  padding-bottom: $course-footer-height;
  background-color: $common-bg;
  .filter{
    filter: blur(6px);
  }
  .shareLayer{
    position: fixed;
    z-index: 4;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    padding: 15px 20px 0 70%;
    overflow: hidden;
    .arrow{
      float: right;
      height: 80px;
    }
    .text{
      float: right;
      height: 70px;
    }
  }
}
</style>
